package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskCollectVO;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    MqttProducer mqttProducer;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }
        checkCreateTask(vm.getVmStatus(),taskViewModel.getProductType());//验证售货机状态
        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }

        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(  vm.getRegionId() );//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
        updateTaskZSet(taskEntity,1);
        return true;
    }

    /**
     * 更新工单量列表
     * @param taskEntity
     * @param score
     */
    private void updateTaskZSet(TaskEntity taskEntity, int score) {
        String roleCode = "1003";//运维
        if (taskEntity.getProductTypeId().intValue()==2){ //补货工单
            roleCode = "1002"; //运营
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+taskEntity.getRegionId()
                +"."+roleCode;
        redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score); // 原子增
    }

    /**
     * 创建工单校验
     * @param vmStatus
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(Integer vmStatus,int productType) throws LogicException {
        //如果是投放工单，状态为运营
        if(productType == VMSystem.TASK_TYPE_DEPLOY  && vmStatus == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_SUPPLY  && vmStatus != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_REVOKE  && vmStatus != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 同一台设备下是否存在未完成的工单
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode,int productionType){
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,innerCode)
                .eq(TaskEntity::getProductTypeId,productionType)
                .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }

    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }


    @Override
    public boolean accept(Long id){
        TaskEntity task = this.getById(id);  //查询工单
        //需要判断当前工单是否是待处理状态，如果不是则抛出异常。
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE){
            throw new LogicException("当前工单状态不是待处理状态");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        if(task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH  || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        updateTaskZSet(task,-1);//取消工单，工单数减一
        return this.updateById(task);
    }

    @Override
    public boolean completeTask(long id) {
        TaskEntity taskEntity = this.getById(id);
        if(taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_FINISH  || taskEntity.getTaskStatus()== VMSystem.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);
        
        //投放、撤机工单发消息
        if (taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_DEPLOY || taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_REVOKE){
            noticeVMServiceStatus(taskEntity);
        }
        //补货工单发消息
        if (taskEntity.getProductTypeId()==VMSystem.TASK_TYPE_SUPPLY){
            noticeVMServiceSupply(taskEntity);
        }
        return true;
    }

    /**
     * 完成运维工单后发消息到emq
     * @param taskEntity
     */
    private void noticeVMServiceStatus(TaskEntity taskEntity) {
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        //发送消息到emq，通知售货机微服务修改状态
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        } catch (Exception e) {
            log.error("发送运维工单完成协议出错");
            throw new LogicException("发送运维工单完成协议出错");
        }
    }

    /**
     * 完成补货工单后发消息到emq
     * @param taskEntity
     */
    private void noticeVMServiceSupply(TaskEntity taskEntity) {
        //根据工单id查询工单明细
        QueryWrapper<TaskDetailsEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TaskDetailsEntity::getTaskId,taskEntity.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(wrapper);
        //构建协议内容，封装协议
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        //补货数据
        List<SupplyChannel> supplyChannels = new ArrayList<>();
        //从工单明细表提取数据到补货数据中
        details.forEach(d->{
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(d.getChannelCode());//货道编号
            supplyChannel.setCapacity(d.getExpectCapacity());//补货数量
            supplyChannels.add(supplyChannel);
        });
        supplyContract.setSupplyData(supplyChannels);
        //发送补货协议到emq
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,supplyContract);
        } catch (Exception e) {
            log.error("发送补货工单完成协议出错");
            throw new LogicException("发送补货工单完成协议出错");
        }
    }

    /**
     *  获取同一天内分配的工单最少的人
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002";
        if (isRepair){ //是运维工单
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." +regionId
                +"."+roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 0);
        if (set==null || set.isEmpty()){
            return 0; //没有数据返回0
        }
        return (Integer) set.stream().collect(Collectors.toList()).get(0);
    }

    /**
     * 统计工单数量
     * @param start 开始时间
     * @param end 结束时间
     * @param repair 是否是运维工单
     * @param taskStatus 工单状态
     * @return
     */
    private int taskCount(LocalDateTime start,LocalDateTime end,Boolean repair,Integer taskStatus){
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        qw.ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        //如果是运维工单
        if (repair){
            qw.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else {
            qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }
        //工单状态为空是查询工单总数
        if (taskStatus!=null){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        return this.count(qw);
    }

    /**
     * 获取工单的统计情况
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskReportInfoVO> getTaskReportInfo(LocalDateTime start, LocalDateTime end) {
        //运营人员工单总数
        var supplyTotal = this.taskCount(start, end, false, null);
        //运维人员工单总数
        var repairTotal = this.taskCount(start, end, true, null);
        //运营人员完成工单
        var supplyComplete = this.taskCount(start, end, false, VMSystem.TASK_STATUS_FINISH);
        //运维人员完成工单
        var repairComplete = this.taskCount(start, end, true, VMSystem.TASK_STATUS_FINISH);
        //运营人员拒绝工单
        var supplyCancel = this.taskCount(start, end, false, VMSystem.TASK_STATUS_CANCEL);
        //运维人员拒绝工单
        var repairCancel = this.taskCount(start, end, true, VMSystem.TASK_STATUS_CANCEL);
        //运营人员总数
        var operatorCount = userService.getOperatorCount();
        //运维人员总数
        var repairerCount = userService.getRepairerCount();

        List<TaskReportInfoVO> list = Lists.newArrayList();
        //运营人员
        var supplyTaskInfo = new TaskReportInfoVO();
        supplyTaskInfo.setTotal(supplyTotal);
        supplyTaskInfo.setCompletedTotal(supplyComplete);
        supplyTaskInfo.setCancelTotal(supplyCancel);
        supplyTaskInfo.setWorkerCount(operatorCount);
        supplyTaskInfo.setRepair(false);
        list.add(supplyTaskInfo);

        //运维人员
        var repairTaskInfo = new TaskReportInfoVO();
        repairTaskInfo.setTotal(repairTotal);
        repairTaskInfo.setCompletedTotal(repairComplete);
        repairTaskInfo.setCancelTotal(repairCancel);
        repairTaskInfo.setWorkerCount(repairerCount);
        repairTaskInfo.setRepair(true);
        list.add(repairTaskInfo);

        return list;
    }

    /**
     * 获取排名前10的工作量
     * @param start
     * @param end
     * @param isRepair
     * @param regionId
     * @return
     */
    @Override
    public List<UserWorkVO> getUserWorkTop10(LocalDate start, LocalDate end, Boolean isRepair, Long regionId) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.select("count(user_id) as user_id,user_name") //聚合查询
                .lambda()
                .ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,end.plusDays(1)) //end时间加一天，防止开始结束时间为同一天查不到数据
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH) //查询完成的工单
                .groupBy(TaskEntity::getUserName)
                .orderByDesc(TaskEntity::getUserId) //完成的工单数倒序排序
                .last("limit 10");
        if (regionId>0){ //传0为查询全部区域
            qw.lambda().eq(TaskEntity::getRegionId,regionId);
        }
        if (isRepair){
            qw.lambda().ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else{
            qw.lambda().eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }
        List<UserWorkVO> result = this.list(qw)
                .stream()
                .map(t -> {
                    UserWorkVO userWorkVO = new UserWorkVO();
                    userWorkVO.setUserName(t.getUserName());
                    userWorkVO.setWorkCount(t.getUserId()); //完成的工单数
                    return userWorkVO;
                }).collect(Collectors.toList());
        return result;
    }

    /**
     * 获取工单报表
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<TaskCollectVO> getTaskReport(LocalDate start, LocalDate end) {
        List<TaskCollectVO> taskCollectVOList=Lists.newArrayList();
        //从开始日期到截至日期，逐条统计
        start.datesUntil(end.plusDays(1), Period.ofDays(1))
                .forEach(date->{
                    var taskCollectVO=new TaskCollectVO();
                    taskCollectVO.setCollectDate(date);
                    taskCollectVO.setProgressCount(count(date,VMSystem.TASK_STATUS_PROGRESS )); //进行中工单数
                    taskCollectVO.setFinishCount(count(date,VMSystem.TASK_STATUS_FINISH ));//完成工单数
                    taskCollectVO.setCancelCount(count(date,VMSystem.TASK_STATUS_CANCEL ));//取消工单数
                    taskCollectVOList.add(taskCollectVO);
                });
        return taskCollectVOList;
    }

    /**
     * 按时间和状态进行统计
     * @param start
     * @param taskStatus
     * @return
     */
    private int count(LocalDate start ,Integer taskStatus){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,start.plusDays(1))
                .eq(TaskEntity::getTaskStatus, taskStatus);
        return this.count(qw);
    }

    /**
     * 获取用户工作量详情
     * @param userId
     * @param start
     * @param end
     * @return
     */
    @Override
    public UserWorkVO getUserWork(Integer userId, LocalDateTime start, LocalDateTime end) {
        var userWork = new UserWorkVO();
        userWork.setUserId(userId);
        //并行处理提高程序吞吐量
        //获取用户完成工单数
        var workCount = this.getCountByUserId(userId,VMSystem.TASK_STATUS_FINISH,start.toLocalDate(),end);
        userWork.setWorkCount(workCount);
        //获取工单总数
        var total = this.getCountByUserId(userId,null,start.toLocalDate(),end);
        userWork.setTotal(total);
        //获取用户拒绝工单数
        var cancelCount = this.getCountByUserId(userId,VMSystem.TASK_STATUS_CANCEL,start.toLocalDate(),end);
        userWork.setCancelCount(cancelCount);
        //获取进行中得工单数
        var progressTotal = this.getCountByUserId(userId,VMSystem.TASK_STATUS_PROGRESS,start.toLocalDate(),end);
        userWork.setProgressTotal(progressTotal);
        return userWork;
    }

    //根据工单状态，获取用户(当月)工单数
    private Integer getCountByUserId(Integer userId,Integer taskStatus,LocalDate start,LocalDateTime end){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        if(taskStatus != null ){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        if(userId != null) {
            qw.eq(TaskEntity::getUserId,userId);
        }
        return this.count(qw);
    }
}
